import sys
import unittest
import warnings
import urllib2
import mechanize

from handler import MechanizeUnitHandler as UnitTestHandler

class MechanizeUnitTest(UnitTestHandler):
    """

    """
    def goto(self, action):
        url = action['value']
        print "Step %s: opening URL %s ..." % (self.step, url)
        self.browser.open(url)

    def verifyTitle(self, action):
        title = action['value']
        print "Step %s: verifying title as '%s' ..." % (self.step, title)
        msg = "Verify Title file:%s step:%s title:'%s' != '%s'" % (
                self.sourceFilename, self.step, title, self.browser.title())
        self.assertEqual(title, self.browser.title(), msg)

    def assertTextExists(self, action):
        text = action["value"]
        print "Step %s: checking for text '%s' in page ..." % (self.step, text)
        msg = "Check Text file:%s step:%s text:'%s'" % (
                self.sourceFilename, self.step, text)
        self.assert_(text in self.responseText, msg)

    def assertTextDoesNotExist(self, action):
        text = action["value"]
        print "Step %s: checking that '%s' does not appear on page ..." % (
            self.step, text)
        msg = "Check Not Text file:%s step:%s text:'%s'" % (
                self.sourceFilename, self.step, text)
        self.assert_(text not in self.responseText, msg)

    def fill(self, action):
        #import pdb;
        #pdb.set_trace()
        xpath = action['xpath']
        form = self.getForm(xpath)
        fieldName = self.getFormElementName(xpath)
        fieldValue = action['value']
        print "Step %s: filling form '%s' with %s=%s ... " % (self.step,
            self.getFormIdentity(xpath), fieldName, fieldValue)
        try:
            self.browser[fieldName] = fieldValue
        except TypeError:
            self.browser[fieldName] = [fieldValue]

    def click(self, action):
        #import pdb; pdb.set_trace()
        try:
            xpath = action['xpath']
            if xpath.startswith("*/FORM"):
                form = self.getForm(xpath)
                fieldName = self.getFormElementName(xpath)
                fieldValue = self.getFormElementValue(xpath)
                print "Step %s: clicking %s=%s on form '%s' ... " % (self.step,
                    fieldName, fieldValue, self.getFormIdentity(xpath))
                if fieldName:
                    clickable = form.find_control(fieldName)
                    if clickable.type == 'radio':
                        for item in clickable.get_items():
                            if item.attrs.get('value') == fieldValue:
                                item.selected = True
                                return
                    else:
                        #import pdb;pdb.set_trace()
                        #request=form.click(id=clickable.id, name=clickable.name)
                        #self.responseText = urllib2.urlopen(request).read()
                        #response = mechanize.urlopen(request)
                        #self.responseText = response.read()
                        
                        response = self.browser.submit(id=clickable.id, 
                                                        name=clickable.name)
                        self.responseText = response.read()
                else:
                    self.responseText = self.browser.submit().read()
            elif '/A[' in xpath:
                linkName = self.getLinkName(xpath)
                print "Step %s: clicking link '%s' ... " % (self.step, linkName)
                self.response = self.browser.follow_link(text=linkName)
                self.responseText = self.response.read()
        except urllib2.URLError, e:
            print "URL: %s, %s" % (e.geturl(), e) 
            raise

    def check(self, action):
        xpath = action['xpath']
        form = self.getForm(xpath)
        name = self.getFormElementName(xpath)
        value = self.getFormElementValue(xpath)
        print "Step %s: checking box %s=%s ..." % (self.step, name, value)
        collection = form.find_control(name, type='checkbox') 
        for item in collection.get_items():
            if (item.attrs.get('value') == value and 
                item.attrs.get('name') == name):
                if action['value'] == 'false':
                    item.selected = False
                elif action['value'] == 'true':
                    item.selected = True
                return

    def select(self, action):
        xpath = action['xpath']
        form = self.getForm(xpath)
        fieldName = self.getFormElementName(xpath)
        fieldValue = action['value']
        print "Step %s: selected %s=%s on form '%s' ... " % (self.step,
            fieldName, fieldValue, self.getFormIdentity(xpath))
        if fieldName:
            selectable = form.find_control(fieldName)
            for item in selectable.get_items():
                if item.attrs.get('value') == fieldValue:
                    item.selected = True
                    return

if __name__ == "__main__":
    filename = sys.argv[1]
    # unittest does some funky stuff with argv apparently....
    sys.argv = sys.argv[:1]
    loader = unittest.TestLoader()
    test = ZopeTestBrowserUnitTest
    test.sourceFilename = filename
    suite = loader.loadTestsFromTestCase(test)
    suite = unittest.TestSuite(suite)
    unittest.TextTestRunner().run(suite)
